<?php
/**
 * 消息推送处理类
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/26
 * Time: 10:03
 */
namespace app\server\controller;


use app\api\model\ThirdApp;
use app\api\model\WorkUser;
use app\api\service\BehaviorMessage;
use GatewayClient\Gateway;

class Push
{
    private  $clientId;
    private  $w_id;
        function __construct($uid)
        {
            //链接地址
            Gateway::$registerAddress = '127.0.0.1:21000';// register 服务地址
            //获取当前用户的client_id
            $data =  Gateway::getClientIdByUid($uid);
            $this->w_id = $uid;
            foreach ($data as $value){
                    if(Gateway::isOnline($value)){
                        $this->clientId = $value;
                        return;
                    }
            }
        }

    /**
     * 推动全部成员
     * @param $data
     * @param string $client_id_array 要推送的成员
     * @param string $exclude_client_id 不要推送的成员
     * @throws \Exception
     */
        public  function sendToAll($data,$client_id_array='',$exclude_client_id=''){
            Gateway::sendToAll($data);
        }

    /**
     * 传递行为
     * @param $news
     * @return bool|int
     * @throws \think\exception\DbException
     */
        public  function  sendToClient($news){
            $clientId = $this->clientId;
            if ($clientId != null){
                //在线推送
                $status =  Gateway::sendToClient($clientId,"$news");
                return $status;
            }
            //离线推送
            $status = $this->sendBehavior($news, $message_data='');
            return $status;
        }

    /**
     * 踢掉某个客户端，并发送信息
     * @param $client_id
     * @param string $massge
     */
        public  function closeClient($massge=''){
            $clientId = $this->clientId;
            Gateway::closeClient($clientId[0],$massge);
        }

    /**
     * 行为传递
     * @param $news
     * @param $message_data
     * @return bool|mixed
     * @throws \think\exception\DbException
     */
    private function sendBehavior($news, $message_data)
    {
        $news = json_decode($news);
        $message_data['message_type'] = $news->message_type;
        $message_data['user_name'] = $news->nickname;
        $message_data['content'] = $news->content;
        $user = WorkUser::get($this->w_id);
        $thirdApp = ThirdApp::getUserInfo($user->t_id);
        $work = $thirdApp->work;
        $message = new BehaviorMessage();
        $result =  $message->sendTextMessage($user, $work, $message_data);
        return $result;
    }

}